package com.opages.netty.demo.netty.rpc.common;

import com.opages.netty.demo.netty.stickybag.MessageProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

/**
 * @author daizhong.liu
 * @create 2021-12-15 14:53
 **/
public class MessageDecoder extends ReplayingDecoder<Void> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        RpcProtocol protocol = new RpcProtocol();
        int[] protocolLen = protocol.getProtocolLen();
        protocolLen[0] = in.readInt();
        protocolLen[1] = in.readInt();
        protocolLen[2] = in.readInt();
        protocolLen[3] = in.readInt();
        protocolLen[4] = in.readInt();
        byte[] headerByte = new byte[protocolLen[0]];
        byte[] classByte = new byte[protocolLen[1]];
        byte[] methodByte = new byte[protocolLen[2]];
        byte[] paramByte = new byte[protocolLen[3]];

        in.readBytes(headerByte);
        in.readBytes(classByte);
        in.readBytes(methodByte);
        in.readBytes(paramByte);

        if(protocolLen[4]>0) {
            byte[] resultByte = new byte[protocolLen[4]];
            in.readBytes(resultByte);
            protocol.setResult(resultByte);
        }
        protocol.setProtocolLen(protocolLen);
        protocol.setHeader(headerByte);
        protocol.setClassName(classByte);
        protocol.setMethodName(methodByte);
        protocol.setParams(paramByte);
        out.add(protocol);
    }
}
